﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using DigibizTree.Picker;
using DigibizTree;
using umbraco.cms.businesslogic.media;
using System.Configuration;
using System.Text;
using System.Security.Cryptography;
using System.Xml.XPath;
using umbraco;
using System.Xml.Linq;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Drawing2D;
using System.IO;
using System.Xml;

using System.Net;

namespace DigibizAdvancedMediaPicker
{
    public partial class SavePixlr : umbraco.BasePages.BasePage
    {
        protected override void OnInit(EventArgs e)
        {
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (Request.QueryString["close"] == "1" || Request.QueryString["id"] == null)
                {
                    Close();
                    return;
                }

                string[] qry = Request.QueryString["id"].Split('|');

                int mediaId;

                if (!int.TryParse(qry[0], out mediaId))
                {
                    Close();
                    return;
                }

                string mediaKey = qry[1];

                //Get the media item from the umbraco cache.
                XPathNodeIterator mediaIterator = library.GetMedia(mediaId, false);

                //Convert the XPathNodeIterator to an XDocument.
                XDocument xmlDocument = XDocument.Parse(mediaIterator.Current.OuterXml);

                //Get the root element.
                XElement mediaElement = xmlDocument.Root;

                if (DigibizMediaHelper.GetMediaMd5Sum(mediaElement) != mediaKey)
                {
                    Close();
                    return;
                }

                string urlImage = Request.QueryString["image"];
                string extension = Path.GetExtension(urlImage);
                if (extension == ".pxd")
                {
                    Close();
                    return;
                }
                string umbracoFile = DigibizMediaHelper.GetFilePathElement(mediaElement).Value;
                string rootDir = HttpContext.Current.Request.PhysicalApplicationPath;
                rootDir = rootDir.Remove(rootDir.Length - 1);

                string mediaPath = Path.GetDirectoryName(umbracoFile.Replace("/", "\\")) + "\\";
                string mediaName = Path.GetFileNameWithoutExtension(umbracoFile) + extension;
                string savePath = rootDir + mediaPath + mediaName;
                string thumbnailPath = rootDir + mediaPath + mediaName.Replace(extension, "_thumb.jpg");

                //Save image.
                WebClient webClient = new WebClient();
                webClient.DownloadFile(urlImage, savePath);

                System.Drawing.Image image = null;

                //Get the saved image for thumbnail use.
                image = System.Drawing.Image.FromFile(savePath);

                //Generate the thumbnail.
                generateThumbnail(image, 100, image.Width, image.Height, thumbnailPath);


                Media media = new Media(mediaId);
                string filePath = mediaPath.Replace("\\", "/") + mediaName;
                FileInfo fileInfo = new FileInfo(savePath);

                //Update all the properties if they are available.
                if (media.getProperty("umbracoFile") != null)
                {
                    media.getProperty("umbracoFile").Value = filePath;
                }
                else if (media.getProperty("fileName") != null)
                {
                    media.getProperty("fileName").Value = filePath;
                }
                else if (media.getProperty("file") != null)
                {
                    media.getProperty("file").Value = filePath;
                }

                if (media.getProperty("umbracoHeight") != null)
                {
                    media.getProperty("umbracoHeight").Value = image.Height.ToString();
                }

                if (media.getProperty("umbracoWidth") != null)
                {
                    media.getProperty("umbracoWidth").Value = image.Width.ToString();
                }

                if (media.getProperty("umbracoBytes") != null)
                {
                    media.getProperty("umbracoBytes").Value = fileInfo.Length.ToString();
                }

                if (media.getProperty("umbracoExtension") != null)
                {
                    media.getProperty("umbracoExtension").Value = extension;
                }

                //Call the save events. We need this to call some DAMP events (cropping etc).
                media.Save();
                media.XmlGenerate(new XmlDocument());

                //Fill the cache again.
                library.GetMedia(media.Id, false);

                //Release all the image resources.
                image.Dispose();


                //Close the popup and update the image in the DAMP property.
                ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "Select", "SetNodeId(" + media.Id + ");", true);
            }
        }

        private void Close()
        {
            //Close the popup without making any changes to the DAMP property.
            ScriptManager.RegisterClientScriptBlock(Page, Page.GetType(), "Close", "Close();", true);
        }

        private void generateThumbnail(System.Drawing.Image image, int maxWidthHeight, int fileWidth, int fileHeight, string thumbnailFileName)
        {
            //Generate thumbnail.
            float fx = (float)fileWidth / (float)maxWidthHeight;
            float fy = (float)fileHeight / (float)maxWidthHeight;

            //Must fit in thumbnail size.
            float f = Math.Max(fx, fy);
            int widthTh = (int)Math.Round((float)fileWidth / f); int heightTh = (int)Math.Round((float)fileHeight / f);

            //Fixes for empty width or height
            if (widthTh == 0)
            {
                widthTh = 1;
            }

            if (heightTh == 0)
            {
                heightTh = 1;
            }

            //Create new image with best quality settings.
            Bitmap bp = new Bitmap(widthTh, heightTh);
            Graphics g = Graphics.FromImage(bp);
            g.SmoothingMode = SmoothingMode.HighQuality;
            g.InterpolationMode = InterpolationMode.HighQualityBicubic;
            g.PixelOffsetMode = PixelOffsetMode.HighQuality;

            //Copy the old image to the new and resized.
            Rectangle rect = new Rectangle(0, 0, widthTh, heightTh);
            g.DrawImage(image, rect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel);

            //Copy metadata.
            ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders();
            ImageCodecInfo codec = null;
            for (int i = 0; i < codecs.Length; i++)
            {
                if (codecs[i].MimeType.Equals("image/jpeg"))
                    codec = codecs[i];
            }

            //Set compresion ratio to 90%.
            EncoderParameters ep = new EncoderParameters();
            ep.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 90L);

            //Save the new image.
            bp.Save(thumbnailFileName, codec, ep);
            bp.Dispose();
            g.Dispose();
        }
    }
}